package com.example.shirodemo.config;

import com.example.shirodemo.filter.MyCustomFilter;
import com.example.shirodemo.real.UserReal;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;


@Configuration
public class ShiroConfig {

    @Bean
    public UserReal myShiroRealm() {
        return new UserReal();
    }

    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 设置realm
        securityManager.setRealm(myShiroRealm());
        return securityManager;
    }

    // 假设你已经有了一个SecurityManager的bean;   org.apache.shiro.mgt.SecurityManager
    @Bean(value = "shiroFilterFactoryBean")
    @Primary
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        // 设置SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 设置Shiro的过滤器链定义，例如：
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/login/**", "anon"); // 允许匿名访问登录页面

        // 配置拦截器
        filterChainDefinitionMap.put("/**", "authc");//过滤器应用于Web应用程序的所有URL请求

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        // 设置登录的URL
        //shiroFilterFactoryBean.setLoginUrl("/login");

        // 设置无权限访问的页面
        //shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");

        // 可以添加更多的自定义过滤器
        Map<String, Filter> filters = new LinkedHashMap<>();
        // 例如添加一个自定义的过滤器
        filters.put("myFilter",new MyCustomFilter());
        shiroFilterFactoryBean.setFilters(filters);
        filterChainDefinitionMap.put("/**","myFilter");
        return shiroFilterFactoryBean;
    }

}
